<template>
<div>
     <fou-dialog :title="'退款'" v-model:dialogValue="dialogValue" :width="'75%'">
      <template #content="">
    <el-form :model="form" label-width="120px" :rules="rules" ref="ruleFormRef">
      <el-row :gutter="24">
        <el-col :span="8">
          <el-form-item label="日期" prop="create_time"><el-input v-model="form.create_time" disabled  /></el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="員工" prop="username"><el-input v-model="form.username" disabled  /></el-form-item>
        </el-col>
        <el-col :span="8">
        </el-col>

        <el-col :span="6">
          <el-form-item label="學生" prop="student_id">
              <el-button v-show="form.student_name" >{{form.student_name}}</el-button>
              <el-button  @click="addStudentTable" type="primary" circle icon="Search"></el-button>
          </el-form-item>
        </el-col>
        <el-col :span="6" >
          <el-form-item label="發票" prop="invoice_id">
              <el-button  @click="addInvoiceTable" type="primary" circle icon="Search"></el-button>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="退款方式" prop="payment">
                <el-select  v-model="form.payment"  size="default" >
                  <el-option v-for="item in payment_options" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
          </el-form-item>
        </el-col>

         <el-col :span="24">
          <el-form-item label="備註" prop="remark">
            <el-col :span="22">
              <el-input type="textarea" v-model="form.remark" ></el-input>
            </el-col>
            <el-col :span="2">
              <el-button type="primary" icon="Search" circle @click="addRemarks('1','remark')">
              </el-button>
            </el-col>
          </el-form-item>
        </el-col>

      </el-row>
          <div v-show="isFlash">
              <div v-if="joinData.course.length>0">
                  <div class="text-lg">課程</div>
                      <ProTable
                        :data="joinData.course"
                        :column="column"
                        :elProps="elProps"
                        :page="[]"
                        :rowControl="[]"
                        :disabled="[]"
                        :controlWidth="[]"
                      >
                            <template #default="{propname,row,index}">
                              <div v-if="propname == 'actual'">
                                <el-input type="number" v-model="row[propname]" :min="1" @change="handlerInput(row[propname],index)" @input="inputSort(row,index)"></el-input>
                              </div>
                            </template>
                      </ProTable>
              </div>
              <div v-if="joinData.product.length>0">
                  <div class="text-lg">產品</div>
                      <ProTable
                        :data="joinData.product"
                        :column="column"
                        :elProps="elProps"
                        :page="[]"
                        :rowControl="[]"
                        :disabled="[]"
                        :controlWidth="[]"
                      >
                            <template #default="{propname,row,index}">
                              <div v-if="propname == 'actual'">
                                <el-input type="number" v-model="row[propname]" :min="1" @change="handlerInput(row[propname],index)" @input="inputSort(row,index)"></el-input>
                              </div>
                            </template>
                      </ProTable>
              </div>
              <div v-if="joinData.products_group.length>0">
                  <div class="text-lg">產品組合</div>
                      <ProTable
                        :data="joinData.products_group"
                        :column="column"
                        :elProps="elProps"
                        :page="[]"
                        :rowControl="[]"
                        :disabled="[]"
                        :controlWidth="[]"
                      >
                            <template #default="{propname,row,index}">
                              <div v-if="propname == 'actual'">
                                <el-input type="number" v-model="row[propname]" :min="1" @change="handlerInput(row[propname],index)" @input="inputSort(row,index)"></el-input>
                              </div>
                            </template>
                      </ProTable>
              </div>
              <div v-if="joinData.ticket.length>0">
                  <div class="text-lg">套票</div>
                      <ProTable
                        :data="joinData.ticket"
                        :column="column"
                        :elProps="elProps"
                        :page="[]"
                        :rowControl="[]"
                        :disabled="[]"
                        :controlWidth="[]"
                      >
                            <template #default="{propname,row,index}">
                              <div v-if="propname == 'actual'">
                                <el-input type="number" v-model="row[propname]" :min="1" @change="handlerInput(row[propname],index)" @input="inputSort(row,index)"></el-input>
                              </div>
                            </template>
                      </ProTable>
              </div>
              <!-- <div class="flex justify-end mt-[15px] pr-[100px]">付款總金額：{{form.refund}}</div> -->
          </div>
    </el-form>

           <div class="flex justify-end mt-10 w-[100%]" >
            <el-button @click="dialogValue = false">取消</el-button>
            <el-button type="primary" @click="confirm(ruleFormRef,buttonType)" color="#081F42">確定</el-button>
           </div>
      </template>
     </fou-dialog>
     <notes ref="notesRef" @update="getNotes"></notes>
     <student ref="studentRef" @update="getStudent"></student>
     <invoice ref="invoiceRef" @update="getInvoice"></invoice>
</div>
</template>

<script setup>
import { ref ,reactive,watch,onMounted} from 'vue' 
import { dayjs } from "element-plus";
import {payment,addRefund,updateRefund,discounts} from '@/http/index.js'
import {message} from '@/common/function.js'
import notes from './notes/notes.vue'
import student from './student/student.vue'
import invoice from './invoice/invoice.vue'
import {elProps,column} from './index'
import { add, subtract, } from 'high-precision-four-fundamental-rules'

const handlerInput = (row,index)=>{
    form.refund = 0
    if (joinData.course) {
       for (let i = 0; i < joinData.course.length; i++) {
      form.refund =  add(parseFloat(joinData.course[i].actual), form.refund, 2)
       }
    }
    if (joinData.product) {
       for (let i = 0; i < joinData.product.length; i++) {
      form.refund =  add(parseFloat(joinData.product[i].actual), form.refund, 2)
       }
    }
    if (joinData.products_group) {
       for (let i = 0; i < joinData.products_group.length; i++) {
      form.refund =  add(parseFloat(joinData.products_group[i].actual), form.refund, 2)
       }
    }
    if (joinData.ticket) {
       for (let i = 0; i < joinData.ticket.length; i++) {
      form.refund =  add(parseFloat(joinData.ticket[i].actual), form.refund, 2)
       }
    }
}
const inputSort = (row,index)=>{
        if (row.actual > (parseFloat(row.grandtotal))) {
          message('付款金額已超出現時尚欠數額，請重新輸入！','error')
          row.actual = parseFloat(row.grandtotal)
        } else if (row.actual < 0) {
          message('請輸入正確金額！','error')
          row.actual  = parseFloat(row.grandtotal)
        }
}



const notesRef = ref('')
const addRemarks = async (type,name)=>{
  await notesRef.value.TableData(type)
  notesRef.value.dialogValue = true
  notesRef.value.name = name
}

const joinData = reactive({
    course:[],
    product:[],
    products_group:[],
    ticket:[]
})
const dialogValue = ref(false)
const rules = reactive({
  student_id: [{ required: true, message: "請選擇學生", trigger: ["blur",'change'] }],
  invoice_id: [{ required: true, message: "請選擇發票", trigger: ["blur",'change'] }],
  payment: [{ required: true, message: "請選擇付款方式", trigger: ["blur",'change'] }],
});
const form = reactive({
    create_time:dayjs().format('YYYY-MM-DD HH:mm:ss'),
    username:localStorage.getItem('username'),
    school_id:localStorage.getItem('school_id'),
    student_name:'',
    invoice_id:'',
    student_id:'',
    refund:0,
    payment:'',
    remark:'',
});
const props = defineProps({
  echo:Object,
})
Object.assign(form,props.echo)
joinData.course = props.echo.course
joinData.product = props.echo.product
joinData.products_group = props.echo.products_group
joinData.ticket = props.echo.ticket
watch(()=>props.echo,(neaval)=>{
  Object.assign(form,neaval)
  console.log(neaval);
joinData.course = neaval.course
joinData.product = neaval.product
joinData.products_group = neaval.products_group
joinData.ticket = neaval.ticket
console.log(joinData);
})
const studentRef = ref('')
const addStudentTable = async()=>{
  await studentRef.value.TableData()
  studentRef.value.studentDia = true
}
const invoiceRef = ref('')
const addInvoiceTable = async()=>{
    if (!form.student_id) {
        message('請添加學生信息','warning')
    }else{
  await invoiceRef.value.TableData(form.student_id)
  invoiceRef.value.dialogValue = true
    }
}

// 添加备注须知信息
const getNotes = (row,name)=>{
    if (name == 'remark') {
      form.remark = row.content
    }
}
// 添加學生信息
const getStudent = (row)=>{
  form.student_name = row.name
  form.student_id = row.id
}

// 添加發票信息
const getInvoice = (row)=>{
  console.log(row);
    form.invoice_id = row.invoice_id
    form.refund = 0
    if (row.course && row.course.length>0) {
      row.course.map(e=>{
      e.number = row.number, e.actual=e.grandtotal
      form.refund =  add(parseFloat(e.grandtotal), form.refund, 2)
      } )
      joinData.course = row.course
    }
    if (row.product && row.product.length>0) {
      row.product.map(e=>{
      e.number = row.number,e.actual=e.grandtotal
      form.refund =  add(parseFloat(e.grandtotal), form.refund, 2)} )
      joinData.product = row.product
    }
    if (row.products_group && row.products_group.length>0) {
      row.products_group.map(e=>{
        e.number = row.number,e.actual=e.grandtotal
      form.refund =  add(parseFloat(e.grandtotal), form.refund, 2)} )
      joinData.products_group = row.products_group
    }
    if (row.ticket && row.ticket.length>0) {
      row.ticket.map(e=>{
        e.number = row.number,e.actual=e.grandtotal
      form.refund =  add(parseFloat(e.grandtotal), form.refund, 2)} )
      joinData.ticket = row.ticket
    }
}
//退款方式
const payment_options = ref([])
const paymentData = async()=>{
    const data = await payment()
    if (data.code == 200) {
        payment_options.value = data.data.data
    }
}
const ruleFormRef = ref('')
const emit = defineEmits(['update'])
const confirm = async (formEl,type) => {
  console.log(joinData);
  if (!formEl) return;
    formEl.validate(async (e)=>{
      if (e) {
        let course = joinData.course.map(e=>({
          name:e.name,number:e.number,create_time:e.create_time,total_prices:e.total_prices,
          grandtotal:e.grandtotal,cid:e.cid,refund:e.actual,actual:e.actual,
          }))
        let product = joinData.product.map(e=>({
          name:e.name,number:e.number,create_time:e.create_time,total_prices:e.total_prices,
          grandtotal:e.grandtotal,cid:e.cid,refund:e.actual,actual:e.actual,
          }))
        let products_group = joinData.products_group.map(e=>({
          name:e.name,number:e.number,create_time:e.create_time,total_prices:e.total_prices,
          grandtotal:e.grandtotal,cid:e.cid,refund:e.actual,actual:e.actual,
          }))
        let ticket = joinData.ticket.map(e=>({
          name:e.name,number:e.number,create_time:e.create_time,total_prices:e.total_prices,
          grandtotal:e.grandtotal,cid:e.cid,refund:e.actual,actual:e.actual,
          }))
        form.item =JSON.stringify({
          course,product,products_group,ticket
        })
        console.log(form);
        if (type == 'add') {
            const data = await addRefund(form)
            if (data.code == 200) {
              message('添加退款成功')
              emit('update')
            }
        }
        if (type == 'edit') {
            const data = await updateRefund(form)
              if (data.code == 200) {
              message('退款成功')
              emit('update')
            }
        }
        dialogValue.value = false
      }
    })
};

const isFlash = ref(true)
const buttonType = ref('')
defineExpose({
    dialogValue,paymentData,isFlash,buttonType
})
</script>

<style lang='less'  scoped>
.el-col{
  padding: 0 !important;
}
.product{
  .el-button{
    color: #fff;
  }
}
</style>